#include "tradeview.h"
#include <QStandardItemModel>
#include <QDebug>
#include "trade.h"

TradeView::TradeView(QObject *parent) :
    QObject(parent)
{
    model=new QStandardItemModel();
}

TradeView::~TradeView()
{
}

void TradeView::getBuyValues(const QString &stockName, Trade *tmpTrade)
{
    BuyTradeValuesDialog* tmpDialog=new BuyTradeValuesDialog(tmpTrade);     //set the buy values of the trade
    tmpDialog->setTradeValues();
    connect(tmpDialog,SIGNAL(acceptedValues(Trade*)),this,SLOT(acceptBuyTradeValues(Trade*)));
    tmpDialog->show();
}

void TradeView::attachTradeTable(QTableView *table)
{
    if(table)
    {
        tradeTable=table;
        getTradeStocks()->show(tradeTable);     //attach the stock model to the trade table
    }
}

void TradeView::disruptTradeTable()
{
    getTradeStocks()->hide();
}

void TradeView::showTradeTable()
{
    tradeTable->show();
}

void TradeView::acceptBuyTradeValues(Trade *tmpTrade)
{
    int row=model->rowCount();
    addTrade(tmpTrade,BUY_TRADE);             //add the buy trade
    setupModel(row,tmpTrade);                //add the trade to the trade table
    tradeTable->setModel(model);            //set the model
}

void TradeView::init()
{
    model=getTradeStocks();                                 //get the model of the stocks, only the set value symbols are shown in this model

    for(int i=0;i<model->rowCount();i++)                    //get the trade information for each stock
    {
        Trade* tmp=getTrade(model->verticalHeaderItem(i)->text());                  //get the trade by the stock name
        qDebug()<<"TradeView::init(): "<<"Current trade: "<<tmp->getStockName();
        //qDebug()<<tmp->getAllItems();
        setupModel(i,tmp);                                                          //setup the model with trade values
    }
}

void TradeView::setupModel(int row,Trade *trade)
{
    int col=2;                                                      //start col for trade values
                                                                    //start at col 2, because the first two cols are for the stock values l10 && t10
    for(int z=0;z<getValSymbols().count();z++)                      //go through the value symbols
    {
        QStandardItem *valItem=trade->getItemMap().value(getValSymbols().at(z));             //get the item with the value in the text attribute
        if(z==0 || valItem->text()=="0")                                                    //do not show stock id or senseless values
            continue;

        QStandardItem* tmp=new QStandardItem();
        tmp->setText(getValNames().at(z));
        model->setHorizontalHeaderItem(col,tmp);
        //qDebug()<<"TradeView::setupModel(): "<<"Füge item mit Symbol "<<getValSymbols().at(z)<<" hinzu";
        model->setItem(row,col,valItem);           //set the trade value in the model
        col++;
    }

    model->setColumnCount(col);               //show only cols with trade values

}
